<?php

namespace app\api\model\gifts;

use app\common\model\gifts\Order as OrderModel;
use app\api\model\gifts\Gifts as GiftsModel;
use app\api\model\gifts\GiftsOrderGoods as GiftsOrderGoodsModel;
use app\common\model\Wxapp as WxappModel;
use app\common\service\Order as OrderService;
use app\common\exception\BaseException;
use app\api\model\gifts\UserGifts as UserGiftsModel;
use app\api\model\dealer\Referee as RefereeModel;
use app\api\model\User as UserModel;
use app\common\library\MysicLog;
use think\Db;

/**
 * 用户充值订单模型
 * Class Order
 * @package app\api\model\recharge
 */
class Order extends OrderModel
{
    /**
     * 隐藏字段
     * @var array
     */
    protected $hidden = [
        'wxapp_id',
    ];

    /**
     * 获取订单详情(待付款状态)
     * @param $orderNo
     * @return self|null
     * @throws \think\exception\DbException
     */
    public static function getPayDetail($orderNo)
    {
        return self::detail(['order_no' => $orderNo, 'pay_status' => 10]);
    }

    /**
     * 创建购买爆品订单
     * @param \app\api\model\User $user 当前用户信息
     * @param int $gifts_id 套餐id
     * @return bool|false|int
     * @throws BaseException
     * @throws \think\exception\DbException
     */
    public function createOrder($user,$gifts_id,$superior_user_id)
    {
        $log = MysicLog::instance();
        $log->setFilename('prepay/gifts');
        // +----------------------------------------------------------------------
        // | 爆品礼预下单开始
        // +----------------------------------------------------------------------
        $log->info('开始', '爆品礼预下单开始');
        // 验证爆品礼数据
        if (!$this->validateForm($user,$gifts_id)) {
            $log->info($this->error ?: '数据验证错误', '数据验证失败');
            $this->error = $this->error ?: '数据验证错误';
            return false;
        }

        $data = $this->getOrderData($user,$gifts_id,$superior_user_id);

        // 创建订单信息
        $this->saveOrder($data);

        return true;
    }

    /**
     * 生成爆品礼订单
     * @param $user
     * @param $rechargeType
     * @param $planId
     * @param $customMoney
     * @return array
     * @throws BaseException
     * @throws \think\exception\DbException
     */
    private function getOrderData($user,$gifts_id,$superior_user_id)
    {
        $log = MysicLog::instance();
        $log->setFilename('prepay/gifts');
        $log->info($superior_user_id, '入参上级ID');
        // +----------------------------------------------------------------------
        // | 获取上级ID
        // +----------------------------------------------------------------------
        $superior_user_id = isset($superior_user_id) ? $superior_user_id : null;
        if($superior_user_id==$user['user_id']){
            $superior_user_id = 0;
        }

        if(!$superior_user_id){
            $superior_user_id = RefereeModel::isExistReferee($user['user_id']);
        }

        $log->info($superior_user_id, '真实上级ID');
        // 订单信息
        $data = [
            'order' => [
                'user_id' => $user['user_id'],
                'superior_user_id' => $superior_user_id,
                'order_no' => OrderService::createOrderNo(),
                'wxapp_id' => self::$wxapp_id,
            ],
            'orderGoods' => []    // 订单套餐快照
        ];
        //获取订单数据
        $this->createOrderData($data, $gifts_id);

        return $data;
    }

    /**
     * 创建订单数据
     * @param $order
     * @param $planId
     * @return bool
     * @throws BaseException
     * @throws \think\exception\DbException
     */
    private function createOrderData(&$order, $gifts_id)
    {
        $log = MysicLog::instance();
        $log->setFilename('prepay/gifts');

        //礼物详情
        $giftsInfo = GiftsModel::apiDetail($gifts_id);

        if (empty($giftsInfo)) {
            throw new BaseException(['msg' => '爆品礼不存在，请刷新后重试']);
        }

        if ($giftsInfo['gifts_stock_num']<1) {
            throw new BaseException(['msg' => '爆品礼库存不足']);
        }

        // +----------------------------------------------------------------------
        // | 上级详情
        // +----------------------------------------------------------------------
        $refereeModel = new UserModel;
        $refereeInfo = $refereeModel::detail($order['order']['superior_user_id']);

        if($refereeInfo){
            $userData = [
                'user_id'=>$refereeInfo['user_id'],
                'nickName'=>$refereeInfo['nickName'],
                'pay_money'=>$refereeInfo['pay_money'],
                'shareholder'=>$refereeInfo['shareholder'],
                'vip_level'=>$refereeInfo['vip_level'],
                'is_staff'=>$refereeInfo['is_staff'],
                'deacler'=>$refereeInfo['deacler'],
            ];
            $log->info($userData, '上级详情');
        }

        // +----------------------------------------------------------------------
        // | 获取当前分销方案一的配置
        // +----------------------------------------------------------------------
        $dealer_setting_one = Db::name("distribution_setting")
            ->where(['wxapp_id'=>$giftsInfo['wxapp_id'],'dealer_type'=>1])
            ->value('setting_content');
        $log->info($dealer_setting_one, '获取当前分销方案一的配置');

        // +----------------------------------------------------------------------
        // | 获取当前分销方案二的配置
        // +----------------------------------------------------------------------
        $dealer_setting_tow = Db::name("distribution_setting")
            ->where(['wxapp_id'=>$giftsInfo['wxapp_id'],'dealer_type'=>2])
            ->value('setting_content');
        $log->info($dealer_setting_tow, '获取当前分销方案二的配置');

        // +----------------------------------------------------------------------
        // | 获取上级用户的单笔支付金额
        // +----------------------------------------------------------------------
        $amount = Db::name("single_order")
            ->where(['wxapp_id'=>$giftsInfo['wxapp_id'],'user_id'=>$order['order']['superior_user_id']])
            ->value('amount');
        $log->info($amount, '获取上级用户的总支付金额');

        // +----------------------------------------------------------------------
        // | 分销开始--获取分销方案
        // +----------------------------------------------------------------------
        $dealer_case = WxappModel::dealerCase($giftsInfo['wxapp_id']);
        $log->info($dealer_case, '获取分销方案');


        //分销价
        $refereePrice = 0;
        if($refereeInfo){
            if($dealer_case==1){
                $checkDealer = $refereeInfo->getConfigByUserType($refereeInfo,$type="gifts");

                $log->info($checkDealer, '获取分销方案一对应的参数');
                if ($checkDealer) {
                    $refereePrice = $giftsInfo['gifts_distribution_price'];//爆品礼物分销价格
                    $log->info($refereePrice, '获取分销方案一的分销价格');
                }else{
                    $log->info("不满足分销条件", '不满足分销条件分销方案一');
                }
            }elseif($dealer_case==2){
                $checkDealer = $refereeInfo->getDealerTow($refereeInfo,$type="gifts_status");
                $log->info($checkDealer, '获取分销方案二对应的参数');
                if($checkDealer){
                    $refereePrice = bcsub($giftsInfo['gifts_price'] * ($checkDealer * 0.01),0, 2);//爆品礼物分销价格
                    $log->info($refereePrice, '获取分销方案二的分销价格');
                }else{
                    $log->info("不满足分销条件", '不满足分销条件分销方案二');
                }
            }

        }else{
            $log->info("没有上级", '不满足分销条件');
        }

        $order['orderGoods'] = $giftsInfo;
        $order['order']['line_price'] = $giftsInfo['gifts_line_price'];//划线价
        $order['order']['order_price'] = $giftsInfo['gifts_price'];//订单金额
        $order['order']['pay_price'] = $giftsInfo['gifts_price'];//实际付款金额
        $order['order']['gifts_distribution_price'] = $refereePrice;//爆品礼物分销价格
        $order['order']['pay_type'] = 20;//支付方式(10余额支付 20微信支付)
        $order['order']['pay_status'] = 10;//付款状态(10未付款 20已付款)
        $order['order']['write_status'] = 10;//付款状态(10未付款 20已付款)
        $order['order']['dealer_case'] = $dealer_case;//分销方案 1 分销方案一  2 分销方案二

        return true;
    }
    /**
     * 保存订单记录
     * @param $data
     * @return bool|false|int
     */
    private function saveOrder($data)
    {
        $log = MysicLog::instance();
        $log->setFilename('prepay/gifts');
        // +----------------------------------------------------------------------
        // | 订单表数据---gifts_order表
        // +----------------------------------------------------------------------
        $log->info($data['order'], '订单表数据');
        // +----------------------------------------------------------------------
        // | 订单快照表数据----gifts_order_goods表
        // +----------------------------------------------------------------------
        $log->info($data['orderGoods'], '订单快照表数据');
        // 写入订单记录
        $this->isUpdate(false)->save($data['order']);
        // 记录订单爆品礼快照
        if (!empty($data['orderGoods'])) {
            $GiftsOrderGoodsModel = new GiftsOrderGoodsModel;
            return $GiftsOrderGoodsModel->add($this['order_id'], $data['orderGoods'],$this['user_id']);
        }
        return true;
    }



    /**
     * 验证爆品礼是否可以购买
     * @param $rechargeType
     * @param $planId
     * @param $customMoney
     * @return bool
     */
    private function validateForm($user,$gifts_id)
    {
        if (empty($gifts_id)) {
            $this->error = '参数错误';
            return false;
        }
        $model = new UserGiftsModel;
        if(!$model->checkBuy($user, $gifts_id)){
            $this->error =  $model->getError();
            return false;
        };
        return true;
    }



}